package Pages;

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.NoSuchElementException;
import selenium.WebDriverWrapper;

import java.util.concurrent.TimeUnit;

/**
 * Created by Time to be on 06.07.2014.
 */
public class SimilarProductsPage extends BasePage {

    private static final String IPhone = "//*[@id='block_with_goods']/div/div[1]/div[%d]/div[1]/div/div/div[%d]/a";
    private static final String IphoneInComparing = "//*[@id='head_banner_container']/div[3]/div/div/div[2]/table/thead/tr[1]/td[%d]/div/div[2]/a";
    private static final By compare = By.name("comparison_details");
    private static final By toCompare = By.xpath("//*[@id='head_banner_container']/div[3]/div/div[1]/div/div[1]/div/div[1]/div/div/div[3]/ul/li[1]/div/a");

    public SimilarProductsPage(WebDriverWrapper driver) {
        super(driver);
        url = "http://rozetka.com.ua/mobile-phones/c80003/filter/preset=smartfon;producer=apple/";
    }

    public boolean Comparing(int first, int second) {
        WebDriverWait wait = new WebDriverWait(driver, 20);
        String firstGood, secondGood;
        int id;
        boolean equal;

        id = xPathCreating(first);

        firstGood = driver.findElement(By.xpath(String.format(IPhone,first, id))).getText();
        driver.findElement(By.xpath(String.format(IPhone,first, id))).click();
        wait.until(ExpectedConditions.elementToBeClickable(toCompare));
        driver.findElement(toCompare).click();

        this.open();
        id = xPathCreating(second);
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(IPhone, second, id))));

        secondGood = driver.findElement(By.xpath(String.format(IPhone, second, id))).getText();
        driver.findElement(By.xpath(String.format(IPhone, second, id))).click();
        driver.findElement(toCompare).click();
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        driver.findElement(toCompare).click();

        wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(IphoneInComparing,2))));

        equal = (   (driver.findElement(By.xpath(String.format(IphoneInComparing,2))).getText() == firstGood)     &&
                    (driver.findElement(By.xpath(String.format(IphoneInComparing, 3))).getText() == secondGood)   );
        return equal;

    }

    private int xPathCreating (int number) {
        int id = 3;
        try {
            driver.findElement(By.xpath(String.format(IPhone, number, id)));
            return id;
            }
        catch (NoSuchElementException e) {
            return id = 2;
            }
        }
//end.
}